import axios from 'axios'
import router from '@/router'
import store from '@/store'
import {Message, MessageBox} from 'element-ui';
import {getToken} from "@/utils/auth";

const service = axios.create({
    baseURL: '/web',
    timeout: 100000
})
service.interceptors.request.use(
    config => {
        const token = getToken();
        if (config.url != '/uum-admin/api/v2/login/webLogin'
            && config.url != '/uum-admin/api/v2/login/giteeUrl'
            && config.url != '/uum-admin/api/v2/login/giteeCallback'
            && token) {
            config.headers['Authorization'] = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    ({data}) => {
        return data
    },
    error => {
        const {code, msg} = error.response.data
        if (code === 'A0230') { // access_token过期，尝试续期token
            Message.error('登陆过期，请重新登陆')
            store.dispatch('logout')
        } else if (code === 'A0231') { // token被禁止访问，添加到黑名单，跳转至登录页
            Message.error('很不辛，您已被管理员强制下线')
            return Promise.reject(new Error(msg || 'Error'))
        }  else {
            Message.error(msg || '系统出错');
            return Promise.reject(new Error(msg || 'Error'));
        }
    }
)

export default service;
